package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private DishMapper dishMapper;

    @Resource
    private SetmealMapper setmealMapper;

    @Override
    public Result<String> addOne(Category category) {
        categoryMapper.insert(category);
        return Result.success("添加分类成功");
    }

    @Override
    public Result<Page<Category>> getPage(int currentPage, int pageSize) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        Page<Category> page = new Page<>(currentPage,pageSize);
        categoryMapper.selectPage(page,queryWrapper);
        return Result.success(page);
    }

    @Override
    public Result<String> deleteOne(Long ids) {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId,ids);
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId,ids);

        long count = dishMapper.selectCount(dishQueryWrapper) + setmealMapper.selectCount(setmealQueryWrapper);
        if(count>0){
            throw new RuntimeException("该分类关联的有菜品或套餐,不能删除");
        }else {
            categoryMapper.deleteById(ids);
            return Result.success("删除成功");
        }
    }

    @Override
    public Result<String> updateById(Category category) {
        categoryMapper.updateById(category);
        return Result.success("修改成功");
    }

    @Override
    public Result<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        return Result.success(categoryList);
    }
}
